package com.git.contractmanagement.service.impl;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PdfPreviewTest {
    
    public static void main(String[] args) {
        // 测试PDF预览图生成
        String uploadDir = "D:/ContractManagement/upload";
        String previewDir = "D:/ContractManagement/preview";
        
        try {
            // 检查upload目录中的PDF文件
            Files.list(Paths.get(uploadDir))
                .filter(path -> path.toString().endsWith(".pdf"))
                .forEach(pdfPath -> {
                    try {
                        System.out.println("处理PDF文件: " + pdfPath);
                        generatePreviewImage(pdfPath.toString(), previewDir);
                    } catch (Exception e) {
                        System.err.println("处理文件失败: " + pdfPath);
                        e.printStackTrace();
                    }
                });
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // 检查preview目录中的文件
        try {
            System.out.println("\npreview目录中的文件:");
            Files.list(Paths.get(previewDir))
                .forEach(path -> System.out.println("  " + path));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private static void generatePreviewImage(String pdfFilePath, String previewDir) throws IOException {
        try (PDDocument document = PDDocument.load(new File(pdfFilePath))) {
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            
            // 只生成第一页的预览图
            BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(0, 150);
            
            // 确保预览目录存在
            Path previewDirPath = Paths.get(previewDir);
            Files.createDirectories(previewDirPath);
            
            // 生成预览图文件名
            String pdfFilename = new File(pdfFilePath).getName();
            String nameWithoutExtension = pdfFilename.lastIndexOf('.') > 0 ? 
                pdfFilename.substring(0, pdfFilename.lastIndexOf('.')) : pdfFilename;
            String previewName = "preview_" + nameWithoutExtension + ".png";
            Path previewPath = previewDirPath.resolve(previewName);
            
            // 写入预览图文件
            ImageIO.write(bufferedImage, "png", previewPath.toFile());
            System.out.println("预览图生成成功: " + previewPath.toString());
        } catch (Exception e) {
            System.err.println("预览图生成失败: " + e.getMessage());
            throw e;
        }
    }
}